package com.hqj.controller;

import com.alibaba.fastjson.JSON;
import com.hqj.entity.Files;
import com.hqj.service.FileServiceI;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Controller
@RequestMapping("/fc")
public class FileController {

    @Resource(name="fileServiceI")
    private FileServiceI fsi;

    @RequestMapping("upload/{tname}/{tid}")
    @ResponseBody
    public String upload(@PathVariable(value = "tname") String tabName,
            @PathVariable(value = "tid") String tabId,
            @RequestParam(value = "file")MultipartFile file){
        Map<String,Object> obj = fsi.uploadFile(file,tabName,tabId);
        return JSON.toJSONString(obj);
    }

    @RequestMapping("/download/{id}")
    public void download(HttpServletRequest req, HttpServletResponse res,
                         @PathVariable(value = "id") int id) throws Exception{

        Files f = new Files();
        f.setId(id);
        f = fsi.get(f);

        String fileName = f.getOldFilename();
        String filePath = f.getFilePath();

        //下载文件名的字符编码格式转换
        fileName = new String(fileName.getBytes("utf-8"),"iso-8859-1");
        //设置网页下载时的文件名称及相应的头文件类型
        res.setCharacterEncoding("utf-8");
        res.setContentType("multipart/form-data");
        res.setHeader("Content-Disposition","attachment;fileName="+fileName);

        try {
            //打开流对象读取文件
            InputStream is = new FileInputStream(filePath);
            //输出流对象
            OutputStream os = res.getOutputStream();
            byte bs[] = new byte[1024];
            int i = 0;
            while ((i=is.read(bs)) > 0){
                os.write(bs,0,i);
            }

            os.close();
            is.close();

        }catch (Exception e){
            System.out.println(e.getMessage());
        }


    }
}
